package dyl.sys.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import dyl.common.util.CryptTool;
import dyl.common.util.JdbcTemplateUtil;
import dyl.sys.bean.SysRoleUser;
import dyl.sys.bean.SysUser;
import dyl.sys.init.AuthCache;
@Service
public class UserService {
	private static Log log = LogFactory.getLog(UserService.class);
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	public SysUser findByUsername(String username) {
		String sql = "select * from sys_user where username=?";
		return jdbcTemplate.queryForBean(sql,new Object[]{username},SysUser.class);
	}
	public SysUser setRoleInUser(SysUser u){
		String sql ="select * from sys_role_user where userid = ?";
		List<SysRoleUser> sysRoleUsers = jdbcTemplate.queryForListBean(sql,new Object[]{u.getId()},SysRoleUser.class);
		BigDecimal roleIds[] = new BigDecimal[sysRoleUsers.size()];
		if(sysRoleUsers!=null&&sysRoleUsers.size()>0){
			for(int i=0;i<sysRoleUsers.size();i++){
				SysRoleUser s = sysRoleUsers.get(i);
				if(s.getRoleid().intValue()<=1){//0,为开发管理员,1为超级管理员
					u.setAdmin(true);
					return u;
				}
				roleIds[i]=s.getRoleid();
			}
			u.setRoleIds(roleIds);
			//将组合权限集合存放到session中
			Map<BigDecimal,Set<BigDecimal>> menuAuthMap =  new HashMap<BigDecimal, Set<BigDecimal>>();
			for (int i = 0; i < roleIds.length; i++) {
				menuAuthMap.putAll(AuthCache.roleAuthMap.get(roleIds[i]));
			}
			for(int i = 0; i < roleIds.length; i++){
				Map<BigDecimal,Set<BigDecimal>>  roleMenuAuthMap =  AuthCache.roleAuthMap.get(roleIds[i]);
				for (Map.Entry<BigDecimal,Set<BigDecimal>> entry : menuAuthMap.entrySet()){
					for (Map.Entry<BigDecimal,Set<BigDecimal>> roleEntry : roleMenuAuthMap.entrySet()){
						if(entry.getKey().equals(roleEntry.getKey())){
							entry.getValue().addAll(roleEntry.getValue());
						}
					}
				}
			}
			log.info("用户:"+u.getId()+"权限:"+menuAuthMap);
			u.setMenuAuthMap(menuAuthMap);
		}
		return u;
	}
	public String userService(String password, String oldPassword,SysUser u) {
		SysUser user =  findByUsername(u.getUsername());
		if (!user.getPassword().equals(CryptTool.md5(oldPassword))){
			return "原密码错误!";
		}
		String sql = "update sys_user set password = ? where id = ?";
		jdbcTemplate.update(sql,new Object[]{CryptTool.md5(password),u.getId()});
		return null;
	}
}
